package com.joylight.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.joylight.bean.Ad;
import com.joylight.controller.api.ApiController;
import com.joylight.dao.AdDao;
import com.joylight.dto.AdDto;
import com.joylight.service.AdService;
import com.joylight.util.FileUtil;

@Service
public class AdServiceImpl implements AdService{
	
	private static Logger logger =  Logger.getLogger(AdServiceImpl.class);
	@Autowired
	private AdDao adDao;
	
	@Value("${adImage.url}")
	private String adImageUrl;
	
	@Value("${adImage.savePath}")
	private String adImageSavePath;
	
	@Override
	public List<AdDto> getByPage(AdDto adDto) {
		List<AdDto> result = new ArrayList<AdDto>();
		Ad condition = new Ad();
		BeanUtils.copyProperties(adDto, condition);
		List<Ad> adList = adDao.selectByPage(condition);
		for (Ad ad : adList) {
			AdDto temp = new AdDto();
			BeanUtils.copyProperties(ad, temp);
			result.add(temp);
		}
		return result;
	}

	@Override
	public boolean add(AdDto adDto) {
		Ad ad = new Ad();
		ad.setTitle(adDto.getTitle());
		ad.setImgFileName(adDto.getImgFileName());
		adDao.insert(ad);
		return true;
	}

	@Override
	public boolean delete(AdDto adDto) {
		
		int result = adDao.delete(adDto.getId());
		if(result > 0) {
			FileUtil.delete(adImageSavePath + adDto.getImgFileName());
			return true;
		}
		return false;
	}
	
}
